package com.gxuwz.medical.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 * @author 演示
 *
 */
public class EncryptUtil {

	/**
	 * sha+md5混合加密
	 * 
	 * @param data
	 * @return
	 */
	public static String md5AndSha(String data) {
		return sha(md5(data));
	}

	/**
	 * md5加密
	 * 
	 * @param inputText
	 * @return
	 */
	public static String md5(String data) {
		return hash(data, "md5");
	}
	/**
	 * sha-1加密
	 * 
	 * @param data
	 * @return
	 */
	public static String sha(String data) {
		return hash(data, "sha-1");
	}
	/**
	 * 加密
	 * @param data
	 * @param algorithmName-md5或者
	 * @return
	 */
	private synchronized static String hash(String data, String algorithmName) {
		if (data == null || "".equals(data.trim())) {
			throw new IllegalArgumentException("Please enter the String to be encrypted");
		}
		if (algorithmName == null || "".equals(algorithmName.trim())) {
			algorithmName = "md5";
		}
		String encryptText = null;
		try {
			MessageDigest digest = MessageDigest.getInstance(algorithmName);
		    digest.update(data.getBytes());
			encryptText=encodeHex(digest.digest());
		} catch (NoSuchAlgorithmException nsae) {
			nsae.printStackTrace();
		} 
		return encryptText;
	}

	/**
	 * 返回十六进制字符串
	 * 
	 * @param arr
	 * @return
	 */
	private static String encodeHex(byte[] bytes) {
        StringBuffer buf = new StringBuffer(bytes.length * 2);
        int i;

        for (i = 0; i < bytes.length; i++) {
            if (((int) bytes[i] & 0xff) < 0x10) {
                buf.append("0");
            }
            buf.append(Long.toString((int) bytes[i] & 0xff, 16));
        }
        return buf.toString();}
	
}
